package com.imooc.project.controller;

import com.imooc.project.dto.LoginDto;
import com.imooc.project.service.AccountService;
import com.imooc.project.service.ResourceService;
import com.imooc.project.vo.ResourceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by HMF on 2021/09/10 15:26
 * <p>
 * 处理登录请求 Controller
 */
@Controller
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private ResourceService resourceService;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String login(String username,
                        String password,
                        HttpSession session,
                        RedirectAttributes attributes,
                        Model model) {
        LoginDto loginDto = accountService.login(username, password);
        String error = loginDto.getError();
        if (error == null) {
            session.setAttribute("account", loginDto.getAccount());
            List<ResourceVO> resourceVOS = resourceService.listResourceByRoleId(loginDto.getAccount().getRoleId());
            model.addAttribute("resources", resourceVOS); /// 返回视图展示的内容数据
        } else {
            attributes.addFlashAttribute("error", error); /// 设置这个在重定向时，就能获取到error的值了
        }

        return loginDto.getPath();
    }

    /**
     * 用户登出
     *
     * @param session 因为登出时，需要注销session
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate(); // 直接销毁session
        return "redirect:/"; // 登出后，重定向到登录页
    }
}
